/* eslint-disable @typescript-eslint/no-var-requires */
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ChildProcess = require('child_process');
const ReadLineSync = require('readline-sync');
const FSJetPackage = require('fs-jetpack');


/** 获取本次要打包的环境 env | test | pro */
function getBuildEnv() {
    return ReadLineSync.question('请选择本次要打包的环境(dev|test|pro) 默认dev: ') || 'dev'
}



/** 获取对应的app_version */
function getAppVersion(env = 'dev') {
    const envVersion = JSON.parse(FSJetPackage.read('./src/assets/version.json') || '{}');
    console.log(`当前${env}环境的version是${envVersion[env + 'Version']}`);
    // 是否升级本次版本
    const willUpdate = (ReadLineSync.question('是否要升级本次版本？（Y/N）默认Y: ') || 'Y') === 'Y';
    if (willUpdate) {
        let currentVersion = envVersion[env + 'Version'];
        currentVersion = Number(currentVersion.replace(/\./g, ''));
        currentVersion++;
        currentVersion = String(currentVersion).split('').join('.');
        console.log(`本次${env}环境升级的版本为${currentVersion}`);
        envVersion[env + 'Version'] = currentVersion;
        FSJetPackage.writeAsync('./src/assets/version.json', JSON.stringify(envVersion));
    }
}


/** 输入打包指令 */
function runCmd(cmd) {
    let ls = ChildProcess.spawn(cmd, { shell: true })
    ls.stdout.on('data', (data) => {
        let msg = data.toString();
        console.log(msg);
    });

    ls.stderr.on('data', (data) => {
        console.log(data.toString());
    });

    ls.on('close', (code) => {
        console.log(code);
    });
}



/** 主函数 */
function main() {
    const env = getBuildEnv();
    if (['dev', 'test', 'pro'].includes(env)) {
        getAppVersion(env);
        runCmd(`cross-env VUE_APP_ENV=${env} cross-env VUE_APP_ISAPP=true vue-cli-service build`);
    }
}


main()